package com.lw.chat.server.handler;

import com.lw.chat.message.LoginRequestMessage;
import com.lw.chat.message.LoginResponseMessage;
import com.lw.chat.server.service.UserServiceFactory;
import com.lw.chat.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        System.out.println("username:"+username+",password:"+password);

        boolean loginFlag = UserServiceFactory.getUserService().login(username,password);
        LoginResponseMessage loginResponseMessage = new LoginResponseMessage(false, "用户名或密码不正确");
        if(loginFlag){
            SessionFactory.getSession().bind(ctx.channel(),username);//channel和username对应起来
            loginResponseMessage = new LoginResponseMessage(true, "登录成功");
        }
        ctx.writeAndFlush(loginResponseMessage);
    }
}
